package com.app.catchgpscoord;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;

import static android.provider.BaseColumns._ID;

public class HandlerSqlite extends SQLiteOpenHelper{
	SQLiteDatabase myDb;
	public HandlerSqlite (Context ctx)	{
		super(ctx,"Coord_DataBase_v2.db",null,1);
		myDb = SQLiteDatabase.openOrCreateDatabase(Environment.getExternalStorageDirectory() + "/external_sd/bases/" + "Coord_DataBase_v2.db", null);
		String str_qry="";
		str_qry+="CREATE TABLE halls_location (";
		str_qry+=_ID+" INTEGER PRIMARY KEY AUTOINCREMENT,";
		str_qry+="type_location text,";
		str_qry+="bulding text,";
		str_qry+="number int,";
		str_qry+="coord_latitude text,";
		str_qry+="coord_length text)";
		Cursor crs = myDb.rawQuery("SELECT count(0) FROM sqlite_master WHERE type='table' AND name='halls_location';", null);
		if(crs.moveToFirst())
		{
			if(crs.getInt(0) == 0)
			{
				myDb.execSQL(str_qry);
			}
		}
	}
	
	
	@Override
	public void onCreate(SQLiteDatabase db)	{
		
	}
	
	@Override
	public void onUpgrade(SQLiteDatabase db, int i_new_version, int i_old_version)	{
		myDb.execSQL("DROP TABLE IF EXISTS ubication");
		myDb.execSQL("DROP TABLE IF EXISTS halls_location");
		onCreate(db);
	}
	
	public long insertRowOnTable_halls_location(String type_location, String bulding, String number, String coord_latitude, String coord_length){
		long count_rows = 0;
		ContentValues values = new ContentValues();
		values.put("type_location",type_location);
		values.put("bulding",bulding);
		values.put("number",number);
		values.put("coord_latitude",coord_latitude);
		values.put("coord_length",coord_length);
		String str_qry="SELECT count(0) FROM halls_location " +
				"WHERE type_location = '"+type_location+"'"+
				" AND bulding = '"+bulding+"'"+
				" AND number = "+number+";";
		Cursor crs = myDb.rawQuery(str_qry,null);
		if(crs.moveToFirst())
		{
			count_rows = crs.getInt(0);
		}
		if (count_rows == 0)
		{
			count_rows = myDb.insert("halls_location", null, values);
		}
		else
		{
			count_rows = -1;
		}
		
		this.close();
		return count_rows;
	}
	
	public void open()	{
		this.getWritableDatabase();
	}
	
	public void close2()	{
		this.close();
	}
	
}
